package com.woniu40.petai_user.web;

import com.sun.imageio.plugins.common.I18N;
import com.woniu40.petai_user.entity.Address;
import com.woniu40.petai_user.entity.Cart;
import com.woniu40.petai_user.entity.Goods;
import com.woniu40.petai_user.entity.User;
import com.woniu40.petai_user.result.ResponseResult;
import com.woniu40.petai_user.service.AddressService;
import com.woniu40.petai_user.service.CartService;
import com.woniu40.petai_user.service.GoodsService;
import org.omg.PortableInterceptor.INACTIVE;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Controller
@RequestMapping("cart")
public class CartController {

    @Autowired
    CartService cartService;
    @Autowired
    GoodsService goodsService;
    @Autowired
    AddressService addressService;

    //根据用户查询购物车列表
    @RequestMapping("/carts")
    public String findCartByUser(HttpSession session, Map map){

        User user = (User) session.getAttribute("user");
        List<Cart> cartList = cartService.findCartsByUserId(user.getUserId());

        map.put("cartList",cartList);
        return "cart";
    }




    @GetMapping("/add")
    @ResponseBody
    public String addCart(Integer goodsId, String goodsName, BigDecimal salePrice, @RequestParam(defaultValue = "1") Integer buyCount, Integer colorId, Integer tasteId, Integer sizeId, HttpSession session){
        String cover = (String) session.getAttribute("cover");
        BigDecimal bigDecimal = new BigDecimal(buyCount.toString());
        BigDecimal allPrice=salePrice.multiply(bigDecimal);
        User user = (User) session.getAttribute("user");
        if (user==null){
            return "goToLogin";
        }else {
//            根据用户的id查询用户的购物车列表
            Integer userId = user.getUserId();
            List<Cart> cartList = cartService.findCartsByUserId(userId);
            Cart cartToUpdate = null;
            //比较是否当前买的商品已经在购物车中存在，如果存在则更新数量，不存在，添加进购物车
            for (Cart cart : cartList) {
                if (cart.getGoodsId()==goodsId
                        &&cart.getColorId()==colorId
                         &&cart.getSizeId()==sizeId
                        &&cart.getTasteId()==tasteId
                        ){
                    cartToUpdate=cart;
                    break;
                }
                System.out.println(cart.getColorId()+"====="+cart.getSizeId()+"====="+cart.getTasteId());
            }

            if(cartToUpdate==null){
            //创建一个购物车对象
            Cart cart = new Cart(null, goodsId, userId,goodsName,salePrice,buyCount, allPrice, colorId, tasteId, sizeId,cover);
            //把购物车信息保存到数据库
            cartService.addCart(cart);
            }else{
                //把当前购买的数量与数据库中的合并
                cartToUpdate.setBuyCount(cartToUpdate.getBuyCount()+buyCount);
                cartToUpdate.setAllPrice(cartToUpdate.getAllPrice().add(allPrice));
                //更新购物车
                cartService.modifyCart(cartToUpdate);
            }

            return "添加购物车成功";
        }

    }



    @RequestMapping("/modifyCart")
    public String modifyCart(Integer cartId,Integer buyCount,HttpSession session,Map map){
        Cart cart = cartService.findCartById(cartId);
        BigDecimal price = cart.getSalePrice();
        BigDecimal newcount = new BigDecimal(buyCount);

        cart.setBuyCount(buyCount);
        cart.setAllPrice(price.multiply(newcount));
        cartService.modifyCart(cart);
        //跳转到购物车页面
        return "redirect:carts";
    }

    @RequestMapping("/removeCarts")
    public String removeCarts(String cartIds){
        cartService.removeBatch(cartIds);
        //跳转到购物车页面
        return "redirect:carts";
    }

    @RequestMapping("/remove")
    public String remove(Integer cartId){
        cartService.remove(cartId);
        //跳转到购物车页面
        return "redirect:carts";
    }

    @RequestMapping("/removeAll")
    public String removeAll(){
        cartService.removeCartAll();
        //跳转到购物车页面
        return "redirect:carts";
    }

    @RequestMapping("/cleanCarts")
    public String cleanCarts(Integer orderId,HttpSession session,Map map){
        cartService.removeByOrderBatch(orderId);

        //查询最新的购物车列表显示
        Integer userId = (Integer) session.getAttribute("userId");
        List<Cart> cartList = cartService.findCartsByUserId(userId);

        map.put("cartList",cartList);
        //跳转到购物车页面
        return "cart";
    }

    @RequestMapping("/goodsToAddress")
    public String toAddress1(Integer buyCount,Map map,HttpSession session) {


        Integer goodsId = (Integer) session.getAttribute("goodsId");
        String name = (String) session.getAttribute("goodsName");
        BigDecimal salePrice = (BigDecimal) session.getAttribute("salePrice");
        String cover = (String) session.getAttribute("cover");

        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "/login.html";
        } else {
            //将商品加入购物车
            Cart cart = new Cart();
            cart.setGoodsId(goodsId);
            cart.setGoodsName(name);
            cart.setSalePrice(salePrice);
            cart.setCover(cover);
            cart.setBuyCount(buyCount);
            BigDecimal total = salePrice.multiply(new BigDecimal(buyCount.toString()));
            cart.setAllPrice(total);
            cartService.addCart(cart);

            List<Cart> cartList = new ArrayList<>();
            cartList.add(cart);
            String cartIds = cart.getCartId().toString();
            //传递给结算页面
            map.put("cartIds", cartIds);
            map.put("cartList", cartList);
            map.put("total", total);
            return "checkout";
        }

    }

        @RequestMapping("/cartToAddress")
        public String cartToAddress(String cartIds,Map map){
            //获取购物车商品信息
            List<Cart> cartList=new ArrayList<>();
            List<Integer> idList = Arrays.stream(cartIds.split(","))
                    .map(s -> Integer.valueOf(s))
                    .collect(Collectors.toList());

            BigDecimal total = new BigDecimal("0.00");

            for (Integer id : idList) {
                Cart cart = cartService.findCartById(id);
                BigDecimal allPrice = cart.getAllPrice();
                total=total.add(allPrice);
                cartList.add(cart);
            }

            //传递给结算页面
            map.put("cartIds",cartIds);
            map.put("cartList",cartList);
            map.put("total",total);

            return "checkout";
        }


   // ==========================自己写===================================

    @RequestMapping("/myCart")
    @ResponseBody
    public ResponseResult<List<Cart>> myCart(HttpSession session){
        User user = (User) session.getAttribute("user");
        List<Cart> cartList = cartService.findCartsByUserId(user.getUserId());
        ResponseResult<List<Cart>> result = new ResponseResult<>();
        result.setCode(200);
        result.setData(cartList);
        result.setMessage("查询成功");
        return result;
    }

    @RequestMapping("/allPrice")
    @ResponseBody
    public ResponseResult allPrice(Integer cartId){
        Cart cart = cartService.findCart(cartId);
        return new ResponseResult<Cart>(200,"成功",cart);
    }

    @RequestMapping("/myCount")
    @ResponseBody
    public ResponseResult MyCount(Integer cartId, Integer buyCount){
        int i = cartService.modifyBuyCount(cartId, buyCount);
        return new ResponseResult<>(200,"更新成功",i);
    }

    @RequestMapping("/removeOrder")
    @ResponseBody
    public ResponseResult removeOrder(Integer cartId, HttpSession session){
        User user = (User) session.getAttribute("user");
        Integer userId = user.getUserId();
        int i = cartService.removeOrder(cartId, userId);
        return new ResponseResult<>(200,"删除成功",i);
    }

    @ResponseBody
    @RequestMapping("/removeAllOrder")
    public ResponseResult removeAllOrder(HttpSession session){
        User user = (User) session.getAttribute("user");
        Integer userId = user.getUserId();
        int i = cartService.removeAllOrder(userId);
        return new ResponseResult<>(200,"清空成功",i);
    }

}
